import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.ServerSocket; import java.net.Socket; public class AlertDataSocket { static final String CRLF = System.getProperty("line.separator"); static ServerSocket server; static int port = 2016; public static void main(String[] args) { try { if (args.length > 0) { String port_V = args[0]; // port if (port_V != null && !"".equals(port_V)) { port = Integer.parseInt(port_V); } } server = new ServerSocket(port); } catch (IOException e) { e.printStackTrace(); } String encoding = "UTF-8"; BufferedReader iReader = null; BufferedWriter iWriter = null; while (true) { Socket client = null; try { client = server.accept(); iReader = new BufferedReader(new InputStreamReader(client .getInputStream(), encoding)); iWriter = new BufferedWriter(new OutputStreamWriter(client .getOutputStream(), encoding)); System.out.println("Receive message: " + iReader.readLine()); sendAck(iWriter); } catch (IOException ex) { sendNack(iWriter); ex.printStackTrace(); } finally { try { if (iWriter != null) { iWriter.close(); } if (iReader != null) { iReader.close(); } if (client != null) { client.close(); } } catch (IOException e) { } } } } public static void sendAck(BufferedWriter iWriter) { String statusLine = "HTTP/1.1 200 OK" + CRLF; String contentTypeLine = "Content-type: text/html" + CRLF; String connectionClose = "Connection: close" + CRLF; String content = "success"; String contentLengthLine = "Content-Length: " + (new Integer(content.length())).toString() + CRLF + CRLF; try { iWriter.write(statusLine); iWriter.write(contentTypeLine); iWriter.write(connectionClose); iWriter.write(contentLengthLine); iWriter.write(content); iWriter.flush(); } catch (IOException ex) { ex.printStackTrace(); } } // Send nack public static void sendNack(BufferedWriter iWriter) { String statusLine = "HTTP/1.1 400 Bad Request" + CRLF; String contentTypeLine = "Content-type: text/html" + CRLF; String connectionClose = "Connection: close" + CRLF; String content = "error"; String contentLengthLine = "Content-Length: " + (new Integer(content.length())).toString() + CRLF + CRLF; try { iWriter.write(statusLine); iWriter.write(contentTypeLine); iWriter.write(connectionClose); iWriter.write(contentLengthLine); iWriter.write(content); iWriter.flush(); } catch (IOException ex) { ex.printStackTrace(); } } }